package com.pdx.service.impl;

import com.pdx.entity.SysPermission;
import com.pdx.mapper.SysPermissionMapper;
import com.pdx.service.PermissionService;
import com.pdx.service.RolePermissionService;
import com.pdx.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author PDX
 * @website https://blog.csdn.net/Gaowumao
 * @Date 2022-05-02 13:27
 * @Description
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private UserRoleService userRoleService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private SysPermissionMapper permissionMapper;

    @Override
    public List<String> getPermissionByUserId(String userId) {
        List<SysPermission> permissions = getPermissions(userId);
        if (permissions.isEmpty() || permissions == null){
            return null;
        }
        List<String> list = new ArrayList<>();
        for (SysPermission permission : permissions) {
            if (!StringUtils.isEmpty(permission.getPerms())){
                list.add(permission.getPerms());
            }
        }
        return list;
    }

    /**
     * 根据用户id查询权限信息
     * @param userId
     * @return
     */
    @Override
    public List<SysPermission> getPermissions(String userId) {
        List<String> roleIdsByUserId = userRoleService.getRoleIdsByUserId(userId);
        if (roleIdsByUserId.isEmpty()){
            return null;
        }
        List<String> permissions = rolePermissionService.getPermissionIdsByRoleIds(roleIdsByUserId);
        if (permissions.isEmpty()){
            return null;
        }
        List<SysPermission> list = permissionMapper.selectByIds(permissions);
        return list;
    }
}
